<template>
  <div class="follow-up-form">
    <!-- 随访标题 -->
    <div class="form-title">随访</div>

    <!-- 表单内容 -->
    <div class="form-content">
      <!-- 第一行：随访渠道和随访时间 -->
      <div class="form-row">
        <div class="form-item">
          <span class="label">随访渠道</span>
          <div class="value-container" style="padding: 8px 4px 4px 12px">
            <el-select
              v-model="patientDetail.followupChannel"
              placeholder="请选择随访渠道" filterable
              class="channel-select"
            >
              <!-- <el-option label="电话" value="phone"></el-option>
              <el-option label="微信" value="wechat"></el-option>
              <el-option label="短信" value="sms"></el-option>
              <el-option label="面谈" value="interview"></el-option>
              <el-option label="邮件" value="email"></el-option> -->
              <el-option
                v-for="value in followupChannel"
                :label="value.text"
                :value="value.value"
                :key="value.text"
              ></el-option>
            </el-select>
          </div>
        </div>
        <div class="form-item">
          <span class="label">随访时间</span>
          <div class="value-container" style="padding: 8px 4px 4px 12px">
            <DatePicker
              v-model="patientDetail.realFollowupDate"
              placeholder="选择随访时间"
              :showIcon="true"
            />
          </div>
        </div>
      </div>

      <!-- 第二行：随访人员 -->
      <div class="form-row">
        <div class="form-item full-width">
          <span class="label">随访人员</span>
          <div class="value-container">
            <!-- <span class="value">{{ patientDetail.followupEmpName }}</span>
            <el-icon class="edit-icon"><Edit /></el-icon> -->
             <el-select
              v-model="patientDetail.followupEmpId" filterable
              placeholder="请选择随访人员"
            >
              <el-option
                v-for="value in feeGetSelect"
                :label="value.empName"
                :value="value.empId"
                :key="value.empName"
              ></el-option>
            </el-select>
          </div>
        </div>
      </div>

      <!-- 第三行：随访结果（多行文本框） -->
      <div class="form-row">
        <div class="form-item full-width">
          <span class="label">随访结果</span>
          <div class="textarea-container">
            <el-input
              v-model="patientDetail.followupResult"
              type="textarea"
              :rows="3"
              placeholder="请输入随访结果"
              class="result-textarea"
            />
          </div>
        </div>
      </div>

      <!-- 第五行：随访附件列表 -->
      <div class="form-row">
        <div class="form-item full-width">
          <span class="label">随访附件</span>
          <div class="attachment-list">
            <div class="attachment-item error">
              <span class="filename—1">
                <el-upload
                  ref="upload"
                  :on-change="handleChange"
                  :auto-upload="false"
                >
                  <div>
                    <el-icon><Upload /></el-icon>
                    上传文件
                  </div>
                </el-upload>
              </span>
            </div>
            <!-- 成功上传的文件 -->
            <div
              class="attachment-item_1 success"
              v-for="(item, index) in imgList"
              :key="item.url"
            >
              <div class="file-left">
                <span class="filename">{{ item.name }}</span>
              </div>
              <div class="file-center">
                <div class="file-status">
                  <el-icon class="success-icon"><SuccessFilled /></el-icon>
                  <span class="status-text">上传成功</span>
                </div>
              </div>
              <div class="file-right">
                <div class="file-actions" @click="onDelImg(item, index)">
                  <el-icon class="delete-icon"><Delete /></el-icon>
                </div>
              </div>
            </div>

            <!-- 上传失败的文件 -->
            <!-- <div class="attachment-item_1 error">
              <div class="file-left">
                <span class="filename">文件名.txt</span>
              </div>
              <div class="file-center">
                <div class="file-status">
                  <el-icon class="error-icon"><CircleCloseFilled /></el-icon>
                  <span class="status-text">文件格式有误</span>
                </div>
              </div>
              <div class="file-right">
                <div class="file-actions">
                  <el-icon class="delete-icon"><Delete /></el-icon>
                </div>
              </div>
            </div> -->
          </div>
        </div>
      </div>

      <!-- 最后一行：记录人和记录时间 -->
      <div class="form-row" v-if="patientDetail.followupStatus != '1'">
        <div class="form-item">
          <span class="label">记录人</span>
          <div class="value-container">
            <span class="value">{{ patientDetail.operatorBy }}</span>
          </div>
        </div>
        <div class="form-item">
          <span class="label">记录时间</span>
          <div class="value-container">
            <span class="value">{{ patientDetail.operateTime }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import { base64Upload ,feeGetSelectList} from '@/api/account';
import {
  Edit,
  DocumentCopy,
  Upload,
  Download,
  Delete,
  SuccessFilled,
  CircleCloseFilled,
} from '@element-plus/icons-vue';
import DatePicker from '@/components/DatePicker/index.vue';
import type { UploadFile, UploadFiles } from 'element-plus';
import stores from '@/store';
import { de } from 'element-plus/es/locales.mjs';
const useBaseDataStore = stores.useBaseDataStore();
const feeGetSelect = ref<any>([]);
const followupChannel = ref<any>([]);
// 上传后的图片 / 附件列表
interface UploadedItem {
  name: string; // 文件名（含后缀）
  path: string; // 服务器返回的路径部分（不含域名）
  ext: string; // 后缀（不含点）
  url: string; // 完整可访问 URL
}
const imgList = ref<UploadedItem[]>([]);

const props = defineProps<{
  patientDetail?: any;
}>();
const patientDetail = ref<any>(null);
watch(
  () => props.patientDetail,
  (newVal) => {
    patientDetail.value = newVal;
    // 处理 attachmentUrls：可能是逗号分隔字符串 / 数组 / 空
    const raw = newVal?.attachmentUrls;
    let urls: string[] = [];
    if (Array.isArray(raw)) {
      urls = raw as string[];
    } else if (typeof raw === 'string') {
      urls = raw
        .split(',')
        .map((s) => s.trim())
        .filter((s) => !!s);
    }
    imgList.value = urls.map((u) => parseFileUrl(u));
  },
  { immediate: true }
);


// 解析文件 URL，拆出文件名 / 扩展名 / path
function parseFileUrl(fileUrl: unknown): UploadedItem {
  const urlStr: string = String(fileUrl ?? '');
  const pureUrl: string = (urlStr.split('?')[0] ?? '') as string;
  const lastSlash: number = pureUrl.lastIndexOf('/');
  const name: string = lastSlash > -1 ? pureUrl.slice(lastSlash + 1) : pureUrl;
  const dotIdx: number = name.lastIndexOf('.');
  const ext: string = dotIdx > -1 ? name.slice(dotIdx + 1).toLowerCase() : '';
  let path: string;
  try {
    const u = new URL(urlStr);
    path = u.pathname;
  } catch {
    path = urlStr.startsWith('/') ? urlStr : '/' + urlStr;
  }
  return { name, path, ext, url: urlStr };
}
// 获取医生下拉数据
const getFeeGetSelectList = async () => {
  const res = await feeGetSelectList();
  //console.log(res);
  if (res.code == 200) {
    feeGetSelect.value = res.data;
  }
};
// 计算属性：过滤后的表格数据
watch(
  () => props.patientDetail,
  (newVal) => {
    followupChannel.value = useBaseDataStore.getEnumSelect(
      'followUpChannelEnum'
    );
    //console.log(followupChannel.value);
    getFeeGetSelectList();
  },
  { immediate: true }
);

//console.log(followupChannel.value);
const base64 = ref<string>(''); // 带前缀 data:image/...
const pureBase64 = ref<string>(''); // 去掉 data:xxx;base64, 的纯部分
// 随访结果文本
const followUpResult = ref('');

// 随访渠道
const followUpChannel = ref('phone');

// 随访时间
const followUpDate = ref('2025-05-02');
const fileToBase64 = (raw: File) =>
  new Promise<string>((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(raw);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = reject;
  });
  // 删除图片
const onDelImg = (item: any, index: number) => {
  imgList.value.splice(index, 1);
};
//文件上传
const handleChange = async (file: UploadFile, fileList: UploadFiles) => {
  // 验证文件类型
  //console.log(file);
  if (!file.raw) return;
  // 如果保留自动上传并且只想在成功后获取：
  // if (file.status !== 'success') return;

  const dataUrl = await fileToBase64(file.raw);
  base64.value = dataUrl;
  // 拆掉前缀（存后端有时只要纯 base64）
  const commaIdx = dataUrl.indexOf(',');
  pureBase64.value = commaIdx > -1 ? dataUrl.slice(commaIdx + 1) : dataUrl;
  //console.log('Base64(data URL):', base64.value);
  //console.log('Pure Base64:', pureBase64.value);
  base64Upload({
    baseStr: base64.value,
    isCompress: false,
  }).then((res) => {
    if (res.code === '200') {
      const data: any = res.data;
      const targetUrl = typeof data === 'string' ? data : data?.url || '';
      const parsed = parseFileUrl(targetUrl);
      if (parsed.url) imgList.value.push(parsed);
      ElMessage.success(res.msg || '上传成功');
    } else {
      //ElMessage.error(res.msg || '上传失败');
    }
  });
  return true;
};
// 上传文件处理
const handleUpload = () => {
  //console.log('上传文件');
  // 实现文件上传逻辑
};

// 下载文件
const handleDownload = (filename: string) => {
  //console.log('下载文件:', filename);
};

// 删除文件
const handleDelete = (filename: string) => {
  //console.log('删除文件:', filename);
};
defineExpose({
 imgList,
 patientDetail,
});

</script>

<style scoped lang="scss">
.follow-up-form {
  background: #ffffff;
  border-radius: 8px;
  width: 100%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.form-title {
  background: #f5f5f5;
  padding: 12px 16px;
  font-family: Microsoft YaHei, sans-serif;
  font-weight: 600;
  font-size: 16px;
  color: #333;
  border-bottom: 1px solid #e5e5e5;
}

.form-content {
  border: 1px solid #e5e5e5;
  border-top: none;
}

.form-row {
  display: flex;
  border-bottom: 1px solid #e5e5e5;

  &:last-child {
    border-bottom: none;
  }
}

.form-item {
  display: flex;
  align-items: flex-start;
  flex: 1;
  padding: 0 16px;
  min-height: 48px;

  &.full-width {
    flex: 1 1 100%;
  }

  &:not(:last-child) {
    border-right: 1px solid #e5e5e5;
  }
}

.label {
  font-family: Microsoft YaHei, sans-serif;
  font-weight: 400;
  font-size: 14px;
  color: #666666;
  min-width: 80px;
  padding: 0 12px 0 0;
  flex-shrink: 0;
  border-right: 1px solid #e5e5e5;
  display: flex;
  align-items: center;
  min-height: 100%;
}

.value-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 14px 0 14px 12px;
}

.channel-select {
  width: 100%;

  :deep(.el-input__wrapper) {
    border: none !important;
    box-shadow: none !important;
    background: transparent;
    padding: 0;

    &.is-focus {
      border: none !important;
      box-shadow: none !important;
    }

    &:hover {
      border: none !important;
      box-shadow: none !important;
    }

    .el-input__inner {
      font-size: 14px;
      color: #333;
      border: none !important;
      outline: none !important;
    }
  }

  :deep(.el-input__suffix) {
    .el-select__caret {
      color: #999;
    }
  }

  :deep(.el-input) {
    border: none !important;
    box-shadow: none !important;
  }
}

.value {
  font-family: Microsoft YaHei, sans-serif;
  font-weight: 400;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.9);
  flex: 1;
}

.edit-icon,
.copy-icon {
  font-size: 16px;
  color: #999;
  cursor: pointer;
  margin-left: 8px;

  &:hover {
    color: #409eff;
  }
}

.textarea-container {
  width: 100%;
  padding: 12px 0 12px 12px;
}

.result-textarea {
  width: 100%;

  :deep(.el-textarea__inner) {
    border: none;
    box-shadow: none;
    resize: none;
    font-size: 14px;

    &::placeholder {
      color: #c0c4cc;
    }
  }
}

.upload-container {
  width: 100%;
  padding: 12px 0 12px 12px;
}

.upload-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  background: #409eff;
  border: none;
  font-size: 14px;
  padding: 8px 16px;

  &:hover {
    background: #66b1ff;
  }
}

.attachment-list {
  width: 100%;
  padding: 8px 0 8px 0px;
  min-height: 80px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.attachment-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 8px;
  border-bottom: 1px solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }
}
.attachment-item_1 {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 8px;
  margin: 8px 8px 0 8px;
  height: 40px;
  background: rgba(0, 0, 0, 0.02);
  border-radius: 6px 6px 6px 6px;

  &:last-child {
    border-bottom: none;
  }
}

.file-left {
  flex: 0 0 200px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.file-center {
  flex: 0 0 120px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin: 0 12px;
}

.file-right {
  flex: 0 0 20px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}
.filename {
  font-size: 14px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
}
.filename—1 {
  font-family: Microsoft YaHei, Microsoft YaHei;
  font-weight: 400;
  font-size: 14px;
  color: #16ada4;
}
.file-status {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 4px;
}

.success-icon {
  color: #67c23a;
  font-size: 16px;
}

.error-icon {
  color: #f56c6c;
  font-size: 16px;
}

.status-text {
  font-size: 12px;
  color: #666;
}

.file-actions {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.download-icon,
.delete-icon {
  font-size: 16px;
  color: #999;
  cursor: pointer;

  &:hover {
    color: #409eff;
  }
}

.delete-icon:hover {
  color: #f56c6c;
}

// 响应式设计
@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
  }

  .form-item {
    border-right: none !important;
    border-bottom: 1px solid #e5e5e5;

    &:last-child {
      border-bottom: none;
    }
  }
}
:deep(.el-upload-list) {
  display: none;
}
</style>
<style lang="scss">
.channel-select {
  .el-select__wrapper {
    padding: 0 !important;
    box-shadow: none !important;
  }
}
</style>
